package cn.edu.nju.software.android.activity;

import java.io.ByteArrayOutputStream;
import java.text.NumberFormat;

import cn.edu.nju.software.android.model.Status;
import cn.edu.nju.software.android.util.ImageUtil;
import cn.edu.nju.software.android.util.LocalFileHelper;
import cn.edu.nju.software.android.widget.MyEditText;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


@SuppressLint("HandlerLeak")
public class PostActivity extends Activity {
	private static final int CAMERA_REQUEST = 1888; 
	private static final int LOCATION_REQUEST = 1928; 

	private String fileName = null;
	private Location location =  null;
	private TextView location_view;
	private boolean locationEnabled = false;
	private boolean gotLocation = false;

	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			if(fileName != null)
				fileName = null;
			Toast.makeText(PostActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
			finish();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_post);

		setText();

		ActionBar actionBar = getActionBar();
		actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE) ;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.post, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case android.R.id.home:
			finish();
			break;
		case R.id.location:
			changeLocationButtonState();
			break;
		case R.id.photo:
			Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
			startActivityForResult(cameraIntent, CAMERA_REQUEST); 
			break;
		case R.id.send:
			EditText editText = (EditText)findViewById(R.id.weibo_content);
			String statusContent = editText.getText().toString();
			if(statusContent.length() <= 0){
				Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
			}else{
				String lat = "0.0";
				String lon = "0.0";
				if(locationEnabled && gotLocation){
					locationEnabled = false;
					gotLocation = false;
					if(location!=null){
						NumberFormat format = NumberFormat.getNumberInstance();
						format.setMaximumFractionDigits(1);
						lat = format.format(location.getLatitude());
						lon = format.format(location.getLongitude());
					}
				}
				Status status = new Status(statusContent, lat, lon);
				if(fileName != null){
					status.upload(fileName, handler);
				}else{
					status.postNewStatus(handler);
				}
			}
			break;
		default:
			return true;
		}
		return false;
	}

	private void changeLocationButtonState(){
		location_view = (TextView) findViewById(R.id.location_view);
		LinearLayout layout = (LinearLayout) findViewById(R.id.post_layout);
		int index = layout.indexOfChild(location_view);
		if (index == -1) {
			if(getLocation()){
				location_view = (TextView) View.inflate(this, R.layout.layout_location, null);
				layout.addView(location_view);
				locationEnabled = true;
				Toast.makeText(this, "打开定位", Toast.LENGTH_SHORT).show();
			}
		} else {
			layout.removeViewAt(index);
			locationEnabled = false;
			gotLocation = false;
			Toast.makeText(this, "关闭定位", Toast.LENGTH_SHORT).show();
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
		if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
			Bitmap photo = (Bitmap)data.getExtras().get("data");
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
			byte[] byteArray = stream.toByteArray();
			fileName = LocalFileHelper.savePic(this, byteArray);
			MyEditText weibo_content = (MyEditText) findViewById(R.id.weibo_content);
			weibo_content.insertDrawable(ImageUtil.resizePic(new BitmapDrawable(null, photo), 300, 300));
		}else if(requestCode == LOCATION_REQUEST && resultCode == RESULT_OK) {
			System.out.println("return from settings");
		}
	}

	private boolean getLocation(){
		LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 

		if ( !locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
			buildAlertMessageNoGps();
		} 
		if ( locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
			Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			if(loc != null)
				setLocation(loc);
			else
				locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 0, new MyLocationListener());
			return true;
		}
		return false;
	}

	private void buildAlertMessageNoGps() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("您的GPS定位没有打开，您想要打开吗？")
		.setCancelable(false)
		.setPositiveButton("打开", new DialogInterface.OnClickListener() {
			public void onClick(final DialogInterface dialog, final int id) {
				startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),LOCATION_REQUEST);
			}
		})
		.setNegativeButton("不", new DialogInterface.OnClickListener() {
			public void onClick(final DialogInterface dialog, final int id) {
				dialog.cancel();
			}
		});
		final AlertDialog alert = builder.create();
		alert.show();
	}

	class MyLocationListener implements LocationListener{

		@Override
		public void onLocationChanged(Location loc) {
			setLocation(loc);
		}

		@Override
		public void onProviderDisabled(String provider) {
			System.out.println(provider);

		}

		@Override
		public void onProviderEnabled(String provider) {
			System.out.println(provider);
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			System.out.println(provider);
		}

	}

	private void setLocation(Location loc){
		location = loc;
		if(locationEnabled && ! gotLocation){
			gotLocation = true;
			location_view.setText("纬度:" + loc.getLatitude() + "\t经度:" + loc.getLongitude());
		}
	}

	private void setText(){
		Bundle bundle = getIntent().getExtras();

		if (bundle!=null){
			String preText = bundle.getString("text","");
			TextView tv = (TextView) findViewById(R.id.weibo_content);
			tv.setText(preText);
		}
	}

}
